import sys
import os

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from game.game_manager import GameManager

_has_pygame = None

def _check_pygame():
    global _has_pygame
    if _has_pygame is not None:
        return _has_pygame
    try:
        import pygame  
        _has_pygame = True
    except Exception:
        _has_pygame = False
    return _has_pygame

def main():
    try:
        game_manager = GameManager()

        if _check_pygame():
            try:
                from ui.advanced_graphics_ui import AdvancedGraphicsUI # type: ignore
                ui = AdvancedGraphicsUI()
                ui.current_team1 = []
                ui.current_team2 = []
                
                ui.run()
                return
            except Exception as e:
                print(f"AdvancedGraphicsUI failed: {e}")
                try:
                    from ui.graphics_ui import GraphicsUI  
                    ui = GraphicsUI()
                    ui.run()
                    return
                except Exception as e:
                    print(f"GraphicsUI failed: {e}")
                    # 继续到文本UI

        from ui.game_ui import GameUI
        ui = GameUI()
        ui.start_game(game_manager)

    except KeyboardInterrupt:
        print("\n\nGame interrupted by user. Goodbye!")
        sys.exit(0)
    except Exception as e:
        print(f"An error occurred: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == "__main__":
    main()